<template>
  <div class="admin-panel">
    <div class="admin-sidebar">
      <div class="sidebar-header">
        <h2>管理后台</h2>
      </div>
      <nav class="sidebar-nav">
        <router-link to="/admin" class="nav-item">
          <el-icon><house /></el-icon>
          概览
        </router-link>
        <router-link to="/admin/users" class="nav-item active">
          <el-icon><user /></el-icon>
          用户管理
        </router-link>
        <router-link to="/admin/games" class="nav-item">
          <el-icon><present /></el-icon>
          游戏管理
        </router-link>
        <router-link to="/admin/forum" class="nav-item">
          <el-icon><chat-dot-round /></el-icon>
          论坛管理
        </router-link>
        <router-link to="/admin/analytics" class="nav-item">
          <el-icon><data-analysis /></el-icon>
          数据分析
        </router-link>
        <router-link to="/" class="nav-item">
          <el-icon><back /></el-icon>
          返回首页
        </router-link>
      </nav>
    </div>
    
    <div class="admin-content">
      <div class="content-header">
        <h1>用户管理</h1>
        <button class="add-btn" @click="showAddUser = true">
          <el-icon><plus /></el-icon>
          添加用户
        </button>
      </div>
      
      <div class="users-table">
        <el-table :data="users" style="width: 100%">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="email" label="邮箱" width="200" />
          <el-table-column prop="role" label="角色" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'primary'">
                {{ scope.row.role === 'admin' ? '管理员' : '用户' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="注册时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <button class="action-btn edit-btn" @click="editUser(scope.row)">
                <el-icon><edit /></el-icon>
                编辑
              </button>
              <button class="action-btn delete-btn" @click="deleteUser(scope.row.id)">
                <el-icon><delete /></el-icon>
                删除
              </button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <!-- 添加用户对话框 -->
    <el-dialog v-model="showAddUser" title="添加用户" width="500px">
      <el-form :model="newUser" :rules="userRules" ref="userForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="newUser.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="newUser.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="newUser.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="newUser.role" placeholder="请选择角色">
            <el-option label="用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddUser = false">取消</el-button>
        <el-button type="primary" @click="addUser">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 编辑用户对话框 -->
    <el-dialog v-model="showEditUser" title="编辑用户" width="500px">
      <el-form :model="editingUser" :rules="userRules" ref="editUserForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editingUser.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editingUser.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editingUser.role" placeholder="请选择角色">
            <el-option label="用户" value="user" />
            <el-option label="管理员" value="admin" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditUser = false">取消</el-button>
        <el-button type="primary" @click="updateUser">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userAPI } from '../api'

export default {
  name: 'UserManagement',
  setup() {
    const users = ref([])
    const showAddUser = ref(false)
    const showEditUser = ref(false)
    const userForm = ref(null)
    const editUserForm = ref(null)
    
    const newUser = reactive({
      username: '',
      email: '',
      password: '',
      role: 'user'
    })
    
    const editingUser = reactive({
      id: null,
      username: '',
      email: '',
      role: 'user'
    })
    
    const userRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ]
    }
    
    const loadUsers = async () => {
      try {
        const response = await userAPI.getUsers()
        if (response.code === 200) {
          users.value = response.data
        }
      } catch (error) {
        console.error('加载用户列表失败:', error)
        ElMessage.error('加载用户列表失败')
      }
    }
    
    const addUser = async () => {
      if (!userForm.value) return
      
      try {
        await userForm.value.validate()
        
        const response = await userAPI.register(newUser)
        if (response.code === 201) {
          ElMessage.success('用户添加成功')
          showAddUser.value = false
          Object.assign(newUser, { username: '', email: '', password: '', role: 'user' })
          loadUsers()
        }
      } catch (error) {
        console.error('添加用户失败:', error)
        ElMessage.error('添加用户失败')
      }
    }
    
    const editUser = (user) => {
      editingUser.id = user.id
      editingUser.username = user.username
      editingUser.email = user.email
      editingUser.role = user.role
      showEditUser.value = true
    }
    
    const updateUser = async () => {
      if (!editUserForm.value) return
      
      try {
        await editUserForm.value.validate()
        
        const response = await userAPI.updateUser(editingUser.id, editingUser)
        if (response.code === 200) {
          ElMessage.success('用户更新成功')
          showEditUser.value = false
          loadUsers()
        }
      } catch (error) {
        console.error('更新用户失败:', error)
        ElMessage.error('更新用户失败')
      }
    }
    
    const deleteUser = async (userId) => {
      try {
        await ElMessageBox.confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await userAPI.deleteUser(userId)
        if (response.code === 200) {
          ElMessage.success('用户删除成功')
          loadUsers()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除用户失败:', error)
          ElMessage.error('删除用户失败')
        }
      }
    }
    
    const formatDate = (date) => {
      if (!date) return '未知'
      return new Date(date).toLocaleString('zh-CN')
    }
    
    onMounted(() => {
      loadUsers()
    })
    
    return {
      users,
      showAddUser,
      showEditUser,
      userForm,
      editUserForm,
      newUser,
      editingUser,
      userRules,
      addUser,
      editUser,
      updateUser,
      deleteUser,
      formatDate
    }
  }
}
</script>

<style scoped>
.admin-panel {
  display: flex;
  min-height: 100vh;
  background: #f5f5f5;
}

.admin-sidebar {
  width: 250px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 0;
  position: fixed;
  height: 100vh;
  left: 0;
  top: 0;
  overflow-y: auto;
}

.sidebar-header {
  padding: 2rem 1.5rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.sidebar-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: bold;
}

.sidebar-nav {
  padding: 1rem 0;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  color: white;
  text-decoration: none;
  padding: 1rem 1.5rem;
  transition: all 0.3s ease;
  border-left: 3px solid transparent;
}

.nav-item:hover {
  background: rgba(255, 255, 255, 0.1);
  border-left-color: white;
}

.nav-item.active {
  background: rgba(255, 255, 255, 0.2);
  border-left-color: white;
}

.admin-content {
  flex: 1;
  margin-left: 250px;
  padding: 2rem;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.content-header h1 {
  color: #333;
  font-size: 2rem;
  margin: 0;
}

.add-btn {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  border: none;
  padding: 0.8rem 1.5rem;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  transition: all 0.3s ease;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(79, 172, 254, 0.4);
}

.users-table {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.action-btn {
  padding: 0.3rem 0.8rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.8rem;
  margin-right: 0.5rem;
  display: inline-flex;
  align-items: center;
  gap: 0.3rem;
  transition: all 0.3s ease;
}

.edit-btn {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
  color: #333;
}

.delete-btn {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.action-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-sidebar {
    width: 200px;
  }
  
  .admin-content {
    margin-left: 200px;
    padding: 1rem;
  }
  
  .content-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }
}

@media (max-width: 480px) {
  .admin-sidebar {
    width: 100%;
    position: relative;
    height: auto;
  }
  
  .admin-content {
    margin-left: 0;
  }
}
</style>